﻿using System;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain.Entity;
using MediatR;
namespace Casamiel.Application.Commands
{
    /// <summary>
    /// App wechat login bind mobile command handler.
    /// </summary>
    public sealed    class AppWechatLoginBindMobileCommandHandler:IRequestHandler<AppWechatLoginBindMobileCommand, ValueTuple<bool, string>>
    {
        private readonly IMemberService _memberService;
        private readonly IWxService _wxService;
        private readonly IMobileCheckCodeService _mobileCheckCode;
        public AppWechatLoginBindMobileCommandHandler( IMemberService memberService,IWxService wxService, IMobileCheckCodeService mobileCheckCode) 
        {
            _memberService = memberService;
            _wxService = wxService;
            _mobileCheckCode = mobileCheckCode;
        }

        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<ValueTuple<bool,string>> Handle(AppWechatLoginBindMobileCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var smsinfo = await _mobileCheckCode.GetByMobileAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
            if (smsinfo == null)
            {
                return new ValueTuple<bool, string>(false, "验证码不对");
            }
            else
            {
                if (smsinfo.Checkcode != request.Yzm)
                {
                    return new ValueTuple<bool, string>(false, "验证码不对");

                }
                if (smsinfo.Checkcode_outdate < DateTime.Now)
                {
                    return  new ValueTuple<bool,string>(false,"验证码已失效");
                }
            }

            //var sucess = _mobileCheckCode.CheckCode(data.mobile, data.yzm, true);

            //if (sucess["Success"].ToString().ToLower() == "false")
            //{
            //    return new JsonResult(new { code = "-2", msg = sucess["msg"].ToString() });
            //}
            var member = await _memberService.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
            if (member == null)
            {
                member = new Member { Mobile = request.Mobile, CreateDate = DateTime.Now, LastLoginDate = DateTime.Now, Source = 1 };
                try
                {
                    await _memberService.AddAsync<ICasaMielSession>(member).ConfigureAwait(false);
                }
                catch (SqlException ex)
                {
                    if (ex.Number == 2627)
                    {
                        member = await _memberService.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
                        member.LastLoginDate = DateTime.Now;
						await _memberService.UpdateLastLoginDateAsync<ICasaMielSession>(member.ID, DateTime.Now).ConfigureAwait(false);
						//await _memberService.UpdateAsync<ICasaMielSession>(member).ConfigureAwait(false);
                    }
                }
            }
            else
            {
                member.LastLoginDate = DateTime.Now;
				await _memberService.UpdateLastLoginDateAsync<ICasaMielSession>(member.ID, DateTime.Now).ConfigureAwait(false);
				//await _memberService.UpdateAsync<ICasaMielSession>(member).ConfigureAwait(false);
            }
            var userinfo = await _wxService.GetByIdAsync<ICasaMielSession>(request.Id).ConfigureAwait(false);
            if (userinfo == null)
            {
                //var json = new JsonErrorResponse
                //{
                //    code = 999,
                //    msg = "很抱歉，出错了"
                //};
                //return new JsonResult(json);

                return new ValueTuple<bool, string>(false, "很抱歉，出错了");
            }

            userinfo.Mobile = request.Mobile;
            userinfo.Update_time = DateTime.Now;
            // Console.WriteLine($"updatewxopeid:{JsonConvert.SerializeObject(userinfo)}");
            await _wxService.UpdateAsync<ICasaMielSession>(userinfo).ConfigureAwait(false);
            //var member = await _memberService.FindAsync<ICasaMielSession>(request.Mobile);
            //if (member == null)
            //{
            //    member = new Member { Mobile = request.Mobile, CreateDate = DateTime.Now, LastLoginDate = DateTime.Now, Source =1 };
            //    await _memberService.AddAsync<ICasaMielSession>(member);
            //}
            return new ValueTuple<bool,string>(true,"");
        }
    }
}
